/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tomasio.projects.welcome.dao;

import com.tomasio.projects.welcome.dto.CameraDTO;
import com.tomasio.projects.welcome.model.Camera;
import com.tomasio.projects.welcome.util.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author administrador
 */
public class HibernateCameraDAO implements CameraDAO {

    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    @Override
    public CameraDTO find(Long id) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Camera camera = (Camera) session.get(Camera.class, id);
        tx.commit();
        session.close();
        return camera.createDTO();
    }

    @Override
    public void create(CameraDTO camera) {
        Camera _camera = new Camera(camera);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.save(_camera);
        tx.commit();
        session.close();
    }

    @Override
    public void remove(Long id) {
        CameraDTO dto = find(id);
        Camera camera = new Camera(dto);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.delete(camera);
        tx.commit();
        session.close();
    }

    @Override
    public void update(CameraDTO camera) {
        Camera _camera = new Camera(camera);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.update(_camera);
        tx.commit();
        session.close();
    }

    @Override
    public List<CameraDTO> findAll() {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        List<Camera> cameras = session.createQuery("from Camera camera").list();
        tx.commit();
        session.close();

        List<CameraDTO> dtoList = new ArrayList<CameraDTO>();
        for (Camera camera : cameras) {
            dtoList.add(camera.createDTO());
        }
        return dtoList;
    }

 
}
